<template>
  <view class="login">
    <view class="backg h1000rpx w750rpx flex-col flex-center">
      <u-image :src="`${$url}/profile/upload/2024/11/18/logo@2x_20241118173344A006.png`" />
    </view>
    <view class="box-border w-full p20rpx">
      <u-button v-if="!openId" text="绑定本机微信" type="primary" @click="ByWechat('bind')" />
      <u-button v-if="openId" text="解除微信绑定" type="primary" @click="ByWechat('')" />
    </view>
  </view>
</template>

<script setup lang='ts' name='user-bindWeChat'>
import { $url, UserApi } from '@/api';
import type { ILoginReq, UserInfo } from '@/api/user/type';
import { useUserStore } from '@/store';
import { Toast } from '@/utils';

// 持久化
const userStore = useUserStore();
userStore.getUserInfo();
const userInfo = computed<UserInfo>(() => {
  return userStore.userInfo || {} as UserInfo;
});

// 获取openId
const openId = computed(() => {
  return userInfo.value?.openId;
});

// 绑定数据表单
const data = ref<ILoginReq>({
  code: openId.value || '',
  stuCode: '',
  password: '',
});
console.log(data.value);

// 微信绑定
const ByWechat = (flag: string) => {
  // 先获取用户信息授权
  uni.getUserProfile({
    desc: '用于绑定微信',
    success: () => {
      // 获取授权后，再进行绑定
      uni.login({
        provider: 'weixin',
        success: (loginRes: any) => {
          data.value.code = loginRes.code;
          // 可以把用户信息一起传给后端
          if (flag === 'bind') {
            UserApi.bindWeChat(data.value)
              .then(() => {
                Toast('绑定成功');
                setTimeout(() => {
                  uni.navigateTo({
                    url: '/pages/user/user',
                  });
                }, 1000);
              })
              .catch((error) => {
                uni.$u.toast(`绑定失败：${error.message}`);
              });
          }
          else {
            UserApi.unbindWeChat(data.value)
              .then(() => {
                Toast('解绑成功');
                userStore.clearUserInfo();
                setTimeout(() => {
                  uni.navigateTo({
                    url: '/subPages/user/login',
                  });
                }, 1000);
              });
          }
        },
        fail: () => {
          uni.$u.toast('微信绑定失败');
        },
      });
    },
    fail: () => {
      uni.$u.toast('用户拒绝授权');
    },
  });
};
</script>

  <style lang='scss' scoped>
  .login{
    .backg{
      // unocss写法 bg-gradient-to-b from-[#168BF2] via-[#168BF2] to-white
      // @apply bg-gradient-to-b from-[#168BF2] via-[#168BF2] to-white;
      background: linear-gradient(to bottom, #168BF2 60%, #FFF 100%);
    }
  }
  </style>
